package common.qiniu

import com.alibaba.fastjson.JSON
import com.jfinal.kit.PropKit
import com.qiniu.common.Zone
import com.qiniu.storage.Configuration
import com.qiniu.storage.UploadManager
import com.qiniu.storage.model.DefaultPutRet
import java.io.File
import com.qiniu.util.Auth



object QiniuUploader {

    private val ACCESS_KEY = PropKit.use("local.properties").get("qn_access_key")
    private val SECRET_KEY = PropKit.use("local.properties").get("qn_secret_key")
    private val BUCKET = PropKit.use("local.properties").get("qn_bucket")
    private val KEY_BASE = ""

    private val config = Configuration(Zone.zone0())
    private val uploadManager = UploadManager(config)

    fun uploadImage(file: File): String?{
        val auth = Auth.create(ACCESS_KEY, SECRET_KEY)
        val upToken = auth.uploadToken(BUCKET)
        val response = uploadManager.put(file, KEY_BASE+"image/"+file.name, upToken)
        if (response.statusCode == 200){
            val putRet = JSON.parseObject(response.bodyString(), DefaultPutRet::class.java)
            return putRet.key
        }
        return null
    }

    fun uploadImages(files: List<File>):List<String>{
        val list = mutableListOf<String>()
        files.forEach {
            val key = uploadImage(it)
            list.add(key ?: "")
        }
        return list
    }
}